<template>
  <img :src="src" ref="img" alt="">
</template>
<script setup>
import { onMounted, useTemplateRef, ref } from 'vue';

const props = defineProps(['data'])

const img = useTemplateRef('img')
const src = ref('https://img.zcool.cn/community/01dcb55ddf5e32a80121597263ce93.gif')

function handleImage() {
  const newImage = new Image()
  newImage.src = props.data
  newImage.onload = () => {
    img.value.src = props.data
  }
  newImage.onerror = () => {
    img.value.src = 'https://img0.baidu.com/it/u=2486752075,2091345777&fm=253&fmt=auto?w=1369&h=800'
  }
}

onMounted(() => {
  if (img.value) {
    const observer = new IntersectionObserver((entirs) => {
      if (entirs[0].intersectionRatio <= 0) return

      handleImage()

      observer.unobserve(img.value)
    })

    observer.observe(img.value)
  }
})
</script>
